<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px">
          <el-col :span="8">
             <el-form-item label="加班日期">
                <el-date-picker
                v-model="alarmdate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>
              </el-form-item>
          </el-col>
          <el-col :span="6">
             <el-form-item  label="客户名称">
              <el-select disabled 
              v-if="this.$store.state.user.fsiteLevel==3"
              v-model="listQuery.fsiteNo" clearable filterable class="filter-item" placeholder="请选择客户名称">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-else v-model="listQuery.fsiteNo" clearable filterable class="filter-item" placeholder="请选择客户名称" @change="getFpointOptionsQuery(listQuery.fsiteNo)">
                  <el-option
                    v-for="item in fsiteNoBelongOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加班人员" prop="userId">
              <el-select style="display: inline-block" clearable filterable v-model="listQuery.userId" class="filter-item" placeholder="请选择加班人员">
                      <el-option
                      v-for="item in getListfpersonQuery"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                    </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
        <el-button  type="primary" @click="handleFilter">查找</el-button>
        <el-button  type="success" @click="handleCreate">添加</el-button>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
       <!-- 查询结果 -->
    <JNPF-table   v-loading="listLoading" :data="list">
      <el-table-column :width="buttonColor.operationThree" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="text"  @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" v-if="scope.row.fbillstate === 1" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="text" v-if="scope.row.fbillstate === 1" @click="audit(scope.row)">确认</el-button>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column v-if="this.$store.state.user.fsiteLevel!=3" :width="buttonColor.name" :formatter="formatSite" align="left" label="客户名称" prop="fsiteNo" />
      <el-table-column :formatter="formatforduser" :width="buttonColor.name" align="left" label="加班人员" prop="userId" />
      <el-table-column :formatter="datetimeFormat" :width="buttonColor.date" align="left" label="开始日期" prop="fbegdate" />
      <el-table-column :formatter="datetimeFormat" :width="buttonColor.date" align="left" label="结束日期" prop="fenddate" />
      <el-table-column align="left" :width="buttonColor.date" label="开始时间" prop="fbegtime" />
      <el-table-column align="left" :width="buttonColor.date" label="结束时间" prop="fendtime" />
      <el-table-column align="left" label="备注" prop="fnote" />
      <el-table-column :width="buttonColor.state" align="left" label="状态" prop="fbillstate">
        <template slot-scope="scope">
          <span
            :style="{color:buttonColor.itemisconfirmed}"
            v-if="scope.row.fbillstate === 1"
            >{{ scope.row.fbillstate | statusFilter }}</span
          >
          <span :style="{color:buttonColor.itemconfirmed}" v-else-if="scope.row.fbillstate === 2">{{
            scope.row.fbillstate | statusFilter
          }}</span>
          <span :style="{color:buttonColor.iteminvalid}" v-else>{{
            scope.row.fbillstate | statusFilter
          }}</span>
        </template>
      </el-table-column>
    </JNPF-table>
    <paginations
      :total="total"
      :page.sync="listQuery.currentPage"
        :limit.sync="listQuery.pageSize"
      />
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="70%">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" ref="dataForm" :model="dataForm" :rules="rules" >
          <el-col :span="12">
            <el-form-item   label="客户名称" prop="fsiteNo">
              <el-select v-model="dataForm.fsiteNo" v-if="this.$store.state.user.fsiteLevel==3" disabled clearable filterable placeholder="请选择客户名称">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-model="dataForm.fsiteNo" v-else :disabled="dialogStatus=='update'" clearable filterable placeholder="请选择客户名称"  @change="getFpointOptions(dataForm.fsiteNo)">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班人员" prop="userId">
                <el-select style="display: inline-block" clearable filterable v-model="dataForm.userId" class="filter-item" placeholder="请选择加班人员">
                  <el-option
                  v-for="item in getListfperson"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="el-form-item-small" label="状态" prop="fbillstate">
              <el-select disabled v-model="dataForm.fbillstate" class="filter-item" placeholder="请选择状态">
                <el-option v-for="item in fbillstate" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item label="加班日期">
              <div style="display:flex">
                <el-date-picker v-model="dataForm.fbegdate" placeholder="开始日期" type="date"/>
                <span>~</span>
                <el-date-picker v-model="dataForm.fenddate" placeholder="结束日期" type="date"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班时间">
               <div style="display:flex">
                <el-time-select
                  v-model="dataForm.fbegtime"
                  :picker-options="{
                     start: '00:00',
                    step: '00:15',
                    end: '23:30'
                  }"
                  placeholder="开始时间">
                </el-time-select>
                <span>~</span>
                <el-time-select
                  v-model="dataForm.fendtime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:15',
                    end: '23:30'
                  }"
                  placeholder="结束时间">
                </el-time-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="text" style="width:100%" label="备注" prop="fnote">
              <el-input v-model="dataForm.fnote"/>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="cancel()">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData" :disabled="dataForm.fbillstate!=1">确定</el-button>
      </span>
    </el-dialog>
    <userDialog :searchVisibleuse.sync="searchVisibleuse"  :fsiteNo.sync="userDialogFsiteNo" :tableColor="tableColor" @userDialog="userDialogValue" />
  </div>
</template>

<script>
import {
  listtcOvertime,
  createtcOvertime,
  updatetcOvertime,
  deletetcOvertime,
} from "@/api/tcOvertime";
import Pagination from "@/components/Pagination";
import {
  tableColor,
  titleColor,
  exportColor,
  buttonColor,
} from "@/filters/index";
import { fsiteOptionsByLevel, getListArea, checkBiz } from "@/api/area";
import UserDialog from "@/components/UserDialog";
import moment from "moment";
const statusMap = {
  1: "待确认",
  2: "已确认",
  8: "已作废",
};
export default {
  name: "ATcOvertime",
  components: { Pagination, UserDialog },
  filters: {
    statusFilter(type) {
      return statusMap[type];
    },
  },
  data() {
    return {
      getListforduser: [],
      alarmdate: null,
      getListfperson: [],
      getListfpersonQuery: [],
      fsiteNoBelongOptions: [],
      userFlag: null,
      searchVisibleuse: false,
      userDialogFsiteNo: null,
      tableColor,
      titleColor,
      buttonColor,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: undefined,
        userId: undefined,
        fbegdate: undefined,
        fenddate: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fnote: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        sort: "create_time",
        order: "desc",
      },
      dataForm: {
        fsiteNo: undefined,
        userId: undefined,
        fbegdate: undefined,
        fenddate: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fnote: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fid: undefined,
      },
      fbillstate: [
        { value: 1, label: "待确认" },
        { value: 2, label: "已确认" },
        { value: 8, label: "已作废" },
      ],
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      rules: {
        fsiteNo: [{ required: true, message: "客户编号不能为空" }],
        userId: [{ required: true, message: "用户编号不能为空" }],
        fbegtime: [{ required: true, message: "开始时间不能为空" }],
        fendtime: [{ required: true, message: "结束时间不能为空" }],
        fbillstate: [{ type: "number", message: "单据状态必须为数字值" }],
      },
    };
  },
  created() {
    this.alarmdate = [
      this.parserDate(moment(new Date().setDate(1)).format("YYYY-MM-DD")),
      new Date(),
    ];
    if (this.$store.state.user.fsiteLevel == 3) {
      this.listQuery.fsiteNo = this.$store.state.user.fsiteNo;
      getListArea({ flag: 13, arg1: this.$store.state.user.fsiteNo })
        .then((response) => {
          this.getListfperson = response.data.data.list;
          this.getListfpersonQuery = response.data.data.list;
        })
        .catch(() => {
          this.getListfperson = [];
          this.getListfpersonQuery = [];
        });
    }
    this.getList();
    fsiteOptionsByLevel(3)
      .then((response) => {
        this.fsiteNoBelongOptions = response.data.data.list;
      })
      .catch(() => {
        this.fsiteNoBelongOptions = [];
      });
    getListArea({ flag: 13 })
      .then((response) => {
        this.getListforduser = response.data.data.list;
      })
      .catch(() => {
        this.getListforduser = [];
      });
  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property];
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD");
    },
    parserDate(date) {
      var t = Date.parse(date);
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, "/")));
      }
    },
    formatDate: function (date) {
      if (typeof date === "object") {
        var ym;
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        if (m < 10) {
          m = "0" + m;
        }
        if (d < 10) {
          d = "0" + d;
        }
        ym = "" + y + "/" + m + "/" + d;
        return ym;
      } else {
        return date;
      }
    },

    // 人员
    formatforduser: function (row, column) {
      if (this.getListforduser) {
        for (let i = 0; i < this.getListforduser.length; i++) {
          if (row.userId == this.getListforduser[i].value) {
            return this.getListforduser[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    // 查找客户改变
    getFpointOptionsQuery(fsiteNo) {
      this.listQuery.userId = undefined;
      this.getListfpersonQuery = [];
      if (fsiteNo) {
        getListArea({ flag: 13, arg1: fsiteNo })
          .then((response) => {
            this.getListfpersonQuery = response.data.data.list;
          })
          .catch(() => {
            this.getListfpersonQuery = [];
          });
      }
    },

    // 添加客户改变
    getFpointOptions(fsiteNo) {
      this.dataForm.userId = undefined;
      this.getListfperson = [];
      if (fsiteNo) {
        getListArea({ flag: 13, arg1: fsiteNo })
          .then((response) => {
            this.getListfperson = response.data.data.list;
          })
          .catch(() => {
            this.getListfperson = [];
          });
      }
    },

    formatSite: function (row, column) {
      if (this.fsiteNoBelongOptions.length > 0) {
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
          if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
            return this.fsiteNoBelongOptions[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },

    // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value;
      if (value === "add") {
        this.userDialogFsiteNo = this.dataForm.fsiteNo;
      } else {
        this.userDialogFsiteNo = this.listQuery.fsiteNo;
      }
      this.searchVisibleuse = true;
    },

    // 人员弹出框返回值
    userDialogValue(value) {
      if (this.userFlag === "add") {
        this.dataForm.userId = value.user.id.toString();
      } else {
        this.listQuery.userId = value.user.id.toString();
      }
    },
    getList() {
      this.listQuery.fbegdate =
        this.alarmdate == null ? null : this.formatDate(this.alarmdate[0]);
      this.listQuery.fenddate =
        this.alarmdate == null ? null : this.formatDate(this.alarmdate[1]);
      this.listLoading = true;
      listtcOvertime(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    cancel() {
      this.dialogFormVisible = false;
    },
    resetForm() {
      this.dataForm = {
        fsiteNo: undefined,
        userId: undefined,
        fbegdate: undefined,
        fenddate: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fnote: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fid: undefined,
      };
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      this.dataForm.fbegdate = new Date();
      this.dataForm.fenddate = new Date();
      this.dataForm.fbegtime = "09:00";
      this.dataForm.fendtime = "06:00";
      this.dataForm.fbillstate = 1;

      if (this.$store.state.user.fsiteLevel == 3) {
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
        this.dataForm.userId = this.$store.state.user.id.toString();
      } else {
        this.getListfperson = [];
      }
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.userId = Number(this.dataForm.userId);
          createtcOvertime(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data);
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "添加加班申请成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response,
              });
            });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      this.dataForm.userId = this.dataForm.userId.toString();
      if (this.$store.state.user.fsiteLevel != 3) {
        getListArea({ flag: 13, arg1: row.fsiteNo })
          .then((response) => {
            this.getListfperson = response.data.data.list;
          })
          .catch(() => {
            this.getListfperson = [];
          });
      }
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.userId = Number(this.dataForm.userId);
          updatetcOvertime(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fid === this.dataForm.fid) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新加班申请成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response,
              });
            });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("是否要删除加班申请", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deletetcOvertime(row)
          .then((response) => {
            this.$notify.success({
              title: "成功",
              message: "删除加班申请成功",
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response,
            });
          });
      });
    },
    audit(row) {
      this.$confirm("是否确定", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("1111111");
          this.dataForm = Object.assign({}, row);
          console.log("2222222222");
          checkBiz({
            pBillNo: this.dataForm.fid,
            pBillState: 2,
            pBizType: "a_tc_overtime",
            pUser: this.$store.state.user.id,
          })
            .then(() => {
              console.log("4444444");
              for (const v of this.list) {
                if (v.fid === this.dataForm.fid) {
                  this.dataForm.fbillstate = 2;
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.$notify.success({
                title: "成功",
                message: "确认成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.data,
              });
            });
        })
        .catch(() => {});
    },
    indexMethod(index) {
      index = index + 1;
      return index;
    },
  },
};
</script>